import VueRouter from "vue-router";
import Vue from "vue";
import Home from "@/pages/Home/index.vue";
import Login from "@/pages/Login/index.vue";
import Register from "@/pages/Register/index.vue";
import Search from "@/pages/Search/index.vue";
import NoFound from "@/pages/NoFound/index.vue";
Vue.use(VueRouter);
import {enhanceRouter} from "@/utils";
import Detail from "@/pages/Detail/index.vue";
import AddCart from "@/pages/AddCart/index.vue";
import Cart from "@/pages/Cart/index.vue";
import Trade from "@/pages/Trade/index.vue";
import Payment from "@/pages/Payment/index.vue";
enhanceRouter("push");
enhanceRouter("replace");
const router = new VueRouter({
    mode:'history',
    scrollBehavior(to){
        if(to.meta.isScroll){
            return {
                x:0,
                y:0
            }
        }
    },
    routes:[
        {
            path:"/",
            component:Home,
            meta:{
                isTypeNav:true,
                isAddCart:true,// 允许进入加入购物车成功界面
            }
        },
        {
            path:'/addCart',
            component:AddCart,
            meta:{
                isAddCart:true,// 允许进入加入购物车成功界面
            },
            beforeEnter(to,from,next){
                console.log(from);
                if(from.meta.isAddCart) next();
                else {
                    alert("您无权进入加入购物车成功界面")
                    next("/");
                }
            }
        },
        {
            path:"/detail/:id.html",
            component:Detail,
            meta:{
                isTypeNav:true,
                isAddCart:true,// 允许进入加入购物车成功界面
            }
        },
        {
            path:"/login",
            component:Login,
            meta:{
                isHideFooter:true
            }
        },
        {
            path:"/register",
            component:Register,
            meta:{
                isHideFooter:true
            }
        },
        {
            path:"/search",
            component:Search,
            meta:{
                isTypeNav:true,
                isAddCart:true,// 允许进入加入购物车成功界面
            }
        },
        {
            path:"*",
            component:NoFound
        },
        {
            path:"/cart",
            component:Cart,
            meta:{
                isTypeNav: true
            }
        },
        {
            path:"/trade",
            component:Trade,
            meta:{
                isAuthorization:true
            }
        },
        {
            path:"/payment",
            component:Payment
        },
    ]
});
router.beforeEach((to,from,next)=>{
    if(to.meta.isAuthorization && !localStorage.getItem("token")){
        next({
            path:"/login",
            query:{
                returnUrl:from.path
            }
        })
    }else next();
})
export default router;